package crawler

import (
	. "crawler/databases"
	"crawler/structure"
	"fmt"
	"log"
	"net/http"
	"net/http/cookiejar"
	"net/url"
	"strconv"
	"strings"
	"time"

	"github.com/PuerkitoBio/goquery"
)

var gCurCookies []*http.Cookie
var gCurCookieJar *cookiejar.Jar

var Cookies string

type Jar struct {
	cookies []*http.Cookie
}

func (jar *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
	jar.cookies = cookies
}
func (jar *Jar) Cookies(u *url.URL) []*http.Cookie {
	return jar.cookies
}

func init() {
	//cookie
	gCurCookies = nil
	gCurCookieJar, _ = cookiejar.New(nil)

	//获取cookie
	getCookie()
}

//获取cookie
func getCookie() {
	fmt.Println("获取cookie\n------------\n-")
	//拿到登入所需要的cookie
	httpReq, err := http.NewRequest("GET", "https://git.cloudwise.com/user/login", nil)
	httpReq.Header.Add("Accept-Language", "zh-CN,zh;q=0.9")
	if err == nil {
		httpClient := &http.Client{
			CheckRedirect: nil,
			Jar:           gCurCookieJar,
		}
		httpClient.Do(httpReq)
		gCurCookies = gCurCookieJar.Cookies(httpReq.URL)
		var cookieNum int = len(gCurCookies)
		for i := 0; i < cookieNum; i++ {
			var curCk *http.Cookie = gCurCookies[i]
			Cookies = Cookies + curCk.Name + "=" + curCk.Value + "; "
		}

		//登入
		if Cookies != "" {
			jar := new(Jar)
			jar.cookies = gCurCookies
			client := &http.Client{nil, nil, jar, 99999999999992}
			_, err := client.PostForm("https://git.cloudwise.com/user/login", url.Values{"user_name": {"tiger.wang"}, "password": {"AIxiaohu12685"}})
			if err == nil {
				// //实时获取数据
				realTimeDataAcquisition()
			} else {
				fmt.Println("登入-失败")
			}
		}
	} else {
		fmt.Println("获取cookie失败")
	}
}

//http抓取
func httpClimb(url string, callback func(data *http.Response)) {
	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	req.Header.Add("cookie", Cookies)
	resp, err := client.Do(req)
	checkError(err)
	callback(resp)
}

func realTimeDataAcquisition() {
	//抓取components路劲,拿到所有组件
	httpClimb("https://git.cloudwise.com/DPMProjects/screen_components/src/master/components", func(data *http.Response) {
		var grabState bool = false
		doc, err := goquery.NewDocumentFromReader(data.Body)
		if err != nil {
			log.Fatal(err)
		}
		//遍历所有组件
		doc.Find("#repo-files-table tbody tr").Each(func(i int, s *goquery.Selection) {
			if !grabState {
				grabState = true
			}
			band := s.Find(".name a").Text()
			if band != "" {
				httpClimb("https://git.cloudwise.com/DPMProjects/screen_components/src/master/components/"+band+"/describe.md", func(data *http.Response) {
					doc, err := goquery.NewDocumentFromReader(data.Body)
					if err != nil {
						log.Fatal(err)
					}
					doc.Find("#file-content .segment .markdown").Each(func(i int, s *goquery.Selection) {
						_primary := band //唯一字段
						SingleConndb("SELECT primarys,version FROM component WHERE primarys=?", _primary, structure.Primary{}, func(rows []string) {
							if len(rows) > 0 { //数据库已有
								_version := interception(s.Find("p:nth-child(5)").Text()) //版本
								if _version != rows[1] {
									_name := interception(s.Find("p:nth-child(2)").Text())     //名称
									_author := interception(s.Find("p:nth-child(1)").Text())   //作者
									_describe := interception(s.Find("p:nth-child(3)").Text()) //描述
									Update("UPDATE component SET `name`='" + _name + "', author='" + _author + "', details='" + _describe + "', version='" + _version + "' WHERE primarys='" + _primary + "'")
								} else {
									fmt.Println("已是最新")
								}
							} else { //数据库暂无
								_name := interception(s.Find("p:nth-child(2)").Text())     //名称
								_author := interception(s.Find("p:nth-child(1)").Text())   //作者
								_describe := interception(s.Find("p:nth-child(3)").Text()) //描述
								// _label := interception(s.Find("p:nth-child(4)").Text())    //标签
								_version := interception(s.Find("p:nth-child(5)").Text()) //版本
								_time := strconv.FormatInt((time.Now().Unix()), 10)
								Add("INSERT INTO component (primarys, `name`, author, details, version, time) VALUES ('" + _primary + "','" + _name + "','" + _author + "','" + _describe + "','" + _version + "','" + _time + "')")
							}
						})
						// //开始爬取图片
						// httpClimb("https://git.cloudwise.com/DPMProjects/screen_components/src/master/components/"+band+"/preview", func(data *http.Response) {
						// 	doc, err := goquery.NewDocumentFromReader(data.Body)
						// 	if err != nil {
						// 		log.Fatal(err)
						// 	}
						// 	doc.Find("#repo-files-table tbody tr td.name").Each(func(i int, s *goquery.Selection) {
						// 		a := s.Find("a").Text()
						// 		fmt.Println(a)
						// 	})
						// })
					})
				})
			}
		})
		if !grabState {
			fmt.Println("抓取失败")
		}

		//定时重复执行
		TimerDemo := time.NewTimer(time.Duration(60) * time.Second)
		select {
		case <-TimerDemo.C:
			fmt.Println("<<-- 定时执行 -->>")
			realTimeDataAcquisition()
		}
	})
}

func checkError(err error) {
	if err != nil {
		log.Fatalf("Get : %v", err)
	}
}

func interception(str string) string {
	_str := ""
	if str != "" {
		_start := strings.Index(str, ":") + (strings.Count(":", "") - 1)
		_end := strings.Index(str, ";")
		_str = str[_start:_end]
	}
	return _str
}
